package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;

public class HttpUrlconnectActivity extends AppCompatActivity {

    private TextView tvResponse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_urlconnect);

        initView();
    }

    private void initView() {
        tvResponse = findViewById(R.id.tv_response_url);
    }
    /*
    向网络发出请求
    view
     */

    public void sendRequestWithHttpUrlConnect(View view){
       new Thread(new Runnable() {
           @Override
           public void run() {
               HttpURLConnection connection = null;
               BufferedReader reader = null;
               try {
                   URL url = new URL("https://www.csdn.net");
                   connection =  (HttpURLConnection) url.openConnection();
                   connection.setRequestMethod("GET");//POST向服务器提交数据
                   connection.setConnectTimeout(5000);
                   connection.setReadTimeout(5000);
                   InputStream in = connection.getInputStream();
                   reader = new BufferedReader(new InputStreamReader(in));

                   StringBuilder response = new StringBuilder();
                   String line;
                   while ((line=reader.readLine())!=null){
                       response.append(line);
                   }

                   showResponse(response.toString());
               } catch (IOException e) {
                   e.printStackTrace();
               } finally {
                   try {
                       if(reader!=null){
                           reader.close();
                       }
                   } catch (IOException e) {
                       e.printStackTrace();
                   }
                   if(connection!=null){
                       connection.disconnect();
                   }
               }
           }
       }).start();

    }

    private void showResponse(String response){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvResponse.setText(response);
            }
        });
    }
}